package com.bearbig.spring.cloud.example.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>网关过滤器</p>
 *
 * @author xiongyu
 * @version $Id: com.bearbig.spring.cloud.example.filter 2017/2/3 17:17 xiongyu $
 */
public class AccessFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        String token = request.getParameter("accessToken");
        if(StringUtils.isEmpty(token)){
            // 不路由
            ctx.setSendZuulResponse(false);
            // http响应码
            ctx.setResponseStatusCode(404);
            // 响应内容，支持html标签
            ctx.setResponseBody("<html><head><title>404</title></head><body><h1>404</h1></body></html>");
        }
        return null;
    }
}
